package view.plugin
{
	//出牌选择框
	
	import event.GlobalEvent;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	import flash3.framework.Singleton;
	
	public class SelectPanel extends Sprite
	{
		private var sprite:Sprite = new Sprite();//
		private var recordX:Number;//记录初始x坐标
		private var recordY:Number;//记录初始y坐标
		private var selectRect:Rectangle;
		private var curRect:Rectangle = new Rectangle();
		private var isSelect:Boolean = false;
		
		public function SelectPanel(rect:Rectangle = null)
		{
			super();
			
			selectRect = new Rectangle();
			selRectange = rect;
			addEventListener(Event.ADDED_TO_STAGE, doSomethingWithStage);
			
		}
		
		private function doSomethingWithStage(evt:Event):void
		{
			stage.addEventListener(MouseEvent.MOUSE_DOWN,downHandler);// 鼠标在舞台上按下时候的事件
			stage.addEventListener(MouseEvent.MOUSE_UP,upHandler);// 鼠标在舞台上放开时的事件.
		}

		///鼠标按下时的函数
		private function downHandler(evt:MouseEvent):void 
		{
			if(isSelect && selectRect.contains(evt.stageX, evt.stageY))
			{
				stage.addEventListener(Event.ENTER_FRAME,loopHandler);
				recordX = mouseX;
				recordY = mouseY;
			}
		}
		//循环
		private function loopHandler(evt:Event):void {
			sprite.graphics.clear();
			sprite.graphics.lineStyle(1,0x000000);
			sprite.graphics.beginFill(0xffffff,.3);
			sprite.graphics.drawRect(recordX,recordY,mouseX-recordX,mouseY-recordY);
			sprite.graphics.endFill();
			curRect.x = recordX; curRect.y = recordY;
			curRect.width = mouseX-recordX; curRect.height = mouseY-recordY;
			addChild(sprite);
		}
		
		public function getSelectRect():Rectangle
		{
			return curRect;
		}
		
		public function get select():Boolean
		{
			return isSelect;
		}
		
		public function set select(sel:Boolean):void
		{
			isSelect = sel;
		}
		
		public function set selRectange(rect:Rectangle):void
		{
			if(!rect) return;
			selectRect.x = rect.x;
			selectRect.y = rect.y;
			selectRect.width = rect.width;
			selectRect.height = rect.height;
		}
		
		//鼠标放开时的函数
		private function upHandler(evt:MouseEvent):void 
		{
			stage.removeEventListener(Event.ENTER_FRAME,loopHandler);
			sprite.graphics.clear();
			var evt1:GlobalEvent = new GlobalEvent(GlobalEvent.MOUSE_UP);
			if(curRect.width < 0)
			{
				curRect.x = curRect.x - Math.abs(curRect.width);
				curRect.width = Math.abs(curRect.width);
			}
			if(curRect.height < 0)
			{
				curRect.y = curRect.y - Math.abs(curRect.height);
				curRect.height = Math.abs(curRect.height);
			}
			evt1.data = curRect.clone();
			curRect.setEmpty();
			curRect.height = 0;
			this.dispatchEvent(evt1);
		}
		
		static public function get i():SelectPanel
		{
			return Singleton.getInstanceOrCreate(SelectPanel) as SelectPanel;
		}
	}
}